package com.ziyun.pop.modules.production.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziyun.pop.common.e.production.FinanceStatusEnum;
import com.ziyun.pop.common.e.production.OrderProductionStatusEnum;
import com.ziyun.pop.modules.erpOrderLog.service.ErpOrderLogService;
import com.ziyun.pop.modules.order.dto.OrderCraftQuoteDto;
import com.ziyun.pop.modules.order.vo.OrderCraftServerVo;
import com.ziyun.pop.modules.production.dao.ErpOrderProductionDao;
import com.ziyun.pop.modules.production.dto.TwbOrderSuppPaymentDto;
import com.ziyun.pop.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.pop.modules.production.service.ErpOrderProductionService;
import com.ziyun.pop.modules.production.vo.ErpOrderProductionListVo;
import com.ziyun.pop.modules.production.vo.OrderSupplierStatisticsVo;
import com.ziyun.pop.modules.production.vo.OrderSupplierVo;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service("erpOrderProductionService")
public class ErpOrderProductionServiceImpl extends ServiceImpl<ErpOrderProductionDao, ErpOrderProductionEntity> implements ErpOrderProductionService {

    @Autowired
    private ErpOrderLogService erpOrderLogService;

    @Override
    public boolean updateByMap(Map<String, Object> map, Integer productionId) {
        int update = this.baseMapper.updateByMap(map, productionId);
        if (update == 0){
            return false;
        }
        return true;
    }

    @Override
    public List<OrderCraftQuoteDto> selectAllotedCraftsList(Integer itemId) {
        return this.baseMapper.selectAllotedCraftsList(itemId);
    }

    @Override
    public List<OrderCraftServerVo> selectAllotedServerCraftsList(Integer erpItemId) {
        return this.baseMapper.selectAllotedServerCraftsList(erpItemId);
    }

    @Override
    public List<ErpOrderProductionListVo> queryProductionList(Map<String, Object> params) {
        return this.baseMapper.queryProductionList(params);
    }

    @Override
    public R queryOrderSupplierPage(Map<String, Object> params) {
        int currPage = params.get("page") == null ? 1: StringUtil.objToInt(params.get("page").toString());
        int pageSize = params.get("limit") == null ? 25: StringUtil.objToInt(params.get("limit").toString());
        Page<OrderSupplierVo> page = new Page<>(currPage, pageSize);
        int totalCounts = baseMapper.countsOrderSupplier(params);
        page.setTotal(totalCounts);
        Long beginPage = (page.getCurrent() - 1) * page.getSize();
        Long size = page.getSize();
        List<OrderSupplierVo> list = baseMapper.queryOrderSupplierList(beginPage.intValue(), size.intValue(), params);
        page.setRecords(list);
        // 订单统计
        long sellerId = (long) params.get("sellerId");
        OrderSupplierStatisticsVo orderSupplierStatisticsVo = baseMapper.twbOrderSupplierStatistics(sellerId);
        return R.ok().put("page", new PageUtils(page)).put("suppStatistics", orderSupplierStatisticsVo);
    }

    @Override
    @Transactional
    public R twbOrderSuppPayment(TwbOrderSuppPaymentDto twbOrderSuppPaymentDto) {
        Integer[] productionIds = twbOrderSuppPaymentDto.getProductionIds();
        List<ErpOrderProductionEntity> erpOrderProductionList = baseMapper.selectList(new QueryWrapper<>(new ErpOrderProductionEntity())
                .in("production_id", productionIds)
                .ne("finance_status", FinanceStatusEnum.PAYD.toInt())
        );
        if (erpOrderProductionList.size() == 0){
            return R.error("未查询到待付款的外协单号");
        }

        List<Integer> ids = erpOrderProductionList.stream().map(ErpOrderProductionEntity::getProductionId).collect(Collectors.toList());
        Integer[] idsArr = new Integer[ids.size()];
        ids.toArray(idsArr);
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("financeStatus", FinanceStatusEnum.PAYD.toInt());
        updateMap.put("financePaytime", twbOrderSuppPaymentDto.getFinancePaytime());
        updateMap.put("financeRemark", twbOrderSuppPaymentDto.getFinanceRemark());
        baseMapper.updateBatchByMap(updateMap, idsArr);

        for (ErpOrderProductionEntity erpOrderProduction : erpOrderProductionList){
            Integer productionId = erpOrderProduction.getProductionId();
            String orderNo = erpOrderProduction.getOrderNo();
            erpOrderLogService.insertOrderItemLog(orderNo, null, "图文宝外协单批量付款：production_id：" + productionId);
        }

        return R.ok();
    }

    @Override
    @Transactional
    public R twbOrderSuppReceiveGoods(Integer[] productionIds) {
        List<ErpOrderProductionEntity> erpOrderProductionList = baseMapper.selectList(new QueryWrapper<>(new ErpOrderProductionEntity())
                .in("production_id", productionIds)
                .ne("production_status", OrderProductionStatusEnum.FINISH.toInt())
        );
        if (erpOrderProductionList.size() == 0){
            return R.error("未查询到生产中的外协单号");
        }

        List<Integer> ids = erpOrderProductionList.stream().map(ErpOrderProductionEntity::getProductionId).collect(Collectors.toList());
        Integer[] idsArr = new Integer[ids.size()];
        ids.toArray(idsArr);
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("productionStatus", OrderProductionStatusEnum.FINISH.toInt());
        baseMapper.updateBatchByMap(updateMap, idsArr);

        for (ErpOrderProductionEntity erpOrderProduction : erpOrderProductionList){
            Integer productionId = erpOrderProduction.getProductionId();
            String orderNo = erpOrderProduction.getOrderNo();
            erpOrderLogService.insertOrderItemLog(orderNo, null, "图文宝外协单批量收货：production_id：" + productionId);
        }

        return R.ok();
    }

    @Override
    public List<ErpOrderProductionListVo> queryTwbProductionList(Map<String, Object> params) {
        return this.baseMapper.queryTwbProductionList(params);
    }

    //根据原始订单号查询生产单
    @Override
    public List<ErpOrderProductionEntity> selectProductionListByOrderNos(List<String> orderNoList) {
        return this.baseMapper.selectProductionListByOrderNos(orderNoList);
    }

}
